package com.glory.brepda.activity.mfg;

import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.glory.brepda.R;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.entity.MLotListEntity;
import com.glory.brepda.entity.MaterielListEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.MyUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MaterielDownActivity extends BaseActivity {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etEqpWork)
    FreeUI_ClearEditText etEqpWork;
    @BindView(R.id.tvMaterielLot)
    TextView tvMaterielLot;
    @BindView(R.id.ivMaterielLotArrow)
    ImageView ivMaterielLotArrow;
    @BindView(R.id.flMaterielLotList)
    FrameLayout flMaterielLotList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.checkbox)
    CheckBox checkBox;
    @BindView(R.id.cbIsCosume)
    CheckBox cbIsCosume;
    @BindView(R.id.etProductmainQTY)
    FreeUI_ClearEditText etProductmainQTY;
    @BindView(R.id.etConsumemainQTY)
    FreeUI_ClearEditText etConsumemainQTY;
    @BindView(R.id.llProductmainQTY)
    LinearLayout llProductmainQTY;
    @BindView(R.id.llConsumemainQTY)
    LinearLayout llConsumemainQTY;
    // 物料加工有效期
    TextView tvFloorLifeExpire;
    // 物料保质期
    TextView tvShelfLifeExpire;

    private List<String> materielLotList;
    private FreeUI_GeneralPop gearPop;
    private String state = "";
    private List<MaterielListEntity.Materiel> mlotlist;
    private boolean isCosume = true;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_materiel_down;
    }

    @Override
    protected void initView() {
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        checkBox.setVisibility(View.VISIBLE);
        setMainLayout(llMain);
        // 物料加工有效期
        tvFloorLifeExpire = findViewById(R.id.tvFloorLifeExpire);
        // 物料保质期
        tvShelfLifeExpire = findViewById(R.id.tvShelfLifeExpire);
        materielLotList = new ArrayList<>();

        String eqpid = getIntent().getExtras().getString("EQPID");
        if (eqpid != null){
            etEqpWork.setText(eqpid);
            requestMaterialList(eqpid);
        }


        initEdit(etEqpWork, s -> requestMaterialList(s));
    }

    private void requestMaterialList(String s) {
        // 清除相关信息
        MyUtils.clearTextInTextView(tvFloorLifeExpire, tvShelfLifeExpire);
        FreeUI_EntityCallBack<BaseResponseBean<MaterielListEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<MaterielListEntity>>
                (new TypeToken<BaseResponseBean<MaterielListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<MaterielListEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                    gearPop = null;
                    materielLotList.clear();
                    mlotlist = response.body().getResponse().getBody().getMLOTLIST();
                    for (MaterielListEntity.Materiel materiel : mlotlist){
                        materielLotList.add(materiel.getMLOTID() + "/" +  materiel.getMAINQTY());
                    }
                    state = response.body().getResponse().getBody().getSTATE();
                    if (response.body().getResponse().getBody().getSTATE().equals("TRUE")){
                        llProductmainQTY.setVisibility(View.VISIBLE);
                        llConsumemainQTY.setVisibility(View.VISIBLE);
                    }else {
                        llProductmainQTY.setVisibility(View.GONE);
                        llConsumemainQTY.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<MaterielListEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"MLOTKITTING");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE","LOAD");
        map.addProperty("EQUIPMENTID",s);
        NetUtils.requestPostNet("IF.MLOTKITTING","GETMLOTKITTING",MaterielDownActivity.this,map,callBack);
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.tvBaseSubmit,R.id.flMaterielLotList})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.tvBaseSubmit:

                if (tvMaterielLot.getText().toString().equals("")){
                    showToast("请选择物料批号",false);
                    return;
                }

                if (cbIsCosume.isChecked()){
                    isCosume = false;
                }else {
                    isCosume = true;
                }

                showSubmitDialog(new onSubmitListener() {
                    @Override
                    public void setOnSubmitListener() {
                        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<JSONObject>>
                                (new TypeToken<BaseResponseBean<JSONObject>>() {
                                }.getType(), getSupportFragmentManager(), this) {

                            @Override
                            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                                super.onSuccess(response);
                                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                                    showToast("物料下机成功", true);
                                    requestMaterialList(getText(etEqpWork));
                                }
                            }

                            @Override
                            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                                super.onError(response);
                                loadError(response.getException(),"MLOTKITTING");
                            }
                        };
                        JsonObject map = new JsonObject();
                        map.addProperty("ACTIONTYPE", "DEASSIGN");
                        map.addProperty("EQUIPMENTID", getText(etEqpWork));
                        map.addProperty("STATE", state);
                        map.addProperty("ISCOSUME", isCosume);
                        map.addProperty("PRODUCTMAINQTY", getText(etProductmainQTY));
                        map.addProperty("CONSUMEMAINQTY", getText(etConsumemainQTY));
//                        map.addProperty("TOWAREHOUSEID", "WareHouse");
                        MLotListEntity mLotListEntity = new MLotListEntity(StringUtils.EMPTY, StringUtils.EMPTY);
                        mLotListEntity.setEQUIPMENTID(getText(etEqpWork));
                        mLotListEntity.setCONSUMETYPE("MATERIAL");
                        mLotListEntity.setSTATE(checkBox.isChecked() ? "SCRAP" : "");
                        for (MaterielListEntity.Materiel data :mlotlist){
                            // 25/4/11 901713 更新mLotListEntity设置mLotId和mainQty逻辑
                            // 通过和集合中的数据匹配出实体类，然后再去设置比较安全
                            // 如果对tvMaterielLot.getText().toString()使用分隔符”/“进行分割出mLotId和mainQty
                            String mLotIdAndQty = data.getMLOTID() + "/" + data.getMAINQTY();
                            if (StringUtils.equals(mLotIdAndQty, tvMaterielLot.getText().toString())){
                                mLotListEntity.setMLOTID(data.getMLOTID());
                                mLotListEntity.setMAINQTY(data.getMAINQTY());
                                mLotListEntity.setPOSITION(data.getPOSITION());
                                break;
                            }
                        }
                        List<MLotListEntity> list = new ArrayList<>();
                        list.add(mLotListEntity);
                        map.add("MLOTLIST", new JsonParser().parse(new Gson().toJson(list)).getAsJsonArray());
                        map.add("XLOTASSEMBLIES", new JsonParser().parse(new Gson().toJson(list)).getAsJsonArray());
                        NetUtils.requestPostNet("IF.MLOTKITTING", "MLOTKITTING3", MaterielDownActivity.this, map, callBack);
                    }
                });
                break;
            case R.id.flMaterielLotList:
                if (materielLotList.size() <= 0){
                    showToast("未获取到物料批次列表",false);
                    return;
                }

                if (gearPop != null) {
                    if (gearPop.isShowing()) {
                        gearPop.dismiss();
                    }
                } else {
                    gearPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flMaterielLotList.getWidth(), materielLotList, ivMaterielLotArrow, (codeS, i) -> {
                        tvMaterielLot.setText(codeS);
                        // 获取物料相关有效期，并设置在相关显示框上面
                        MaterielListEntity.Materiel mLotData = getMLotData();
                        if (mLotData != null) {
                            tvFloorLifeExpire.setText(mLotData.getFLOORLIFEEXPIRE());
                            tvShelfLifeExpire.setText(mLotData.getSHELFLIFEEXPIRE());
                        }
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivMaterielLotArrow);
                gearPop.showAsDropDown(flMaterielLotList, 0, 0);
                break;
        }

    }

    /**
     * 根据选择的物料在列表里面筛选并返回匹配到的信息
     * @return MaterielListEntity.Materiel 相关信息
     */
    private MaterielListEntity.Materiel getMLotData() {
        if (mlotlist == null || mlotlist.size() == 0) {
            return null;
        }

        for (MaterielListEntity.Materiel data : mlotlist){
            // 25/4/11 901713 更新mLotListEntity设置mLotId和mainQty逻辑
            // 通过和集合中的数据匹配出实体类，然后再去设置比较安全
            // 如果对tvMaterielLot.getText().toString()使用分隔符”/“进行分割出mLotId和mainQty
            String mLotIdAndQty = data.getMLOTID() + "/" + data.getMAINQTY();
            if (StringUtils.equals(mLotIdAndQty, tvMaterielLot.getText().toString())){
               return data;
            }
        }
        return null;
    }
}
